<template>
  <common-edit-dialog
    :title="`${isTypeEdit ? '编辑分类' : '新增分类'}`"
    :visible.sync="isTypeDialog"
    :button-loading="dialogLoading"
    @cancel="typeDialogCancel"
    @submit="persistenceTypeForm"
  >
    <el-form
      ref="typeForm"
      :model="typeForm"
      :rules="typeRule"
      label-width="80px"
      @submit.native.prevent
    >
      <el-form-item label="分类名称" prop="name">
        <common-input :maxlength="20" v-model="typeForm.name"></common-input>
      </el-form-item>
    </el-form>
  </common-edit-dialog>
</template>

<script>
import { typeTreeAdd, typeTreeEdit, typeTreeDelete } from "@/api/datascan/alarmRules/rules";
export default {
  props: {
    isTypeEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      typeForm: {
        id: null,
        name: "",
        parentId: 0,
        status: null,
      },
      typeRule: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
      },
      dialogLoading: false,
      isTypeDialog: false,
    };
  },

  methods: {
    show(data) {
      this.isTypeDialog = true;
      if(data && data.id){
        this.typeForm.name = data.name;
        this.typeForm.id = data.id;
      }else{
        this.typeForm.name = "";
        this.typeForm.id = null;
      }
    },
    persistenceTypeForm() {
      this.$refs.typeForm.validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          if (this.isTypeEdit) {
            typeTreeEdit(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("重命名成功");
                  this.isTypeDialog = false;
                  this.$emit("toQueryAllTree");
                } else {
                  this.$GlobalErrorConfirm("重命名失败", res.msg);
                }
              })
              .finally(() => (this.dialogLoading = false));
          } else {
            typeTreeAdd(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.isTypeDialog = false;
                  this.$emit("toQueryAllTree");
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => (this.dialogLoading = false));
          }
        }
      });
    },
    typeDialogCancel() {
      this.isTypeDialog = false;
    },
  },
};
</script>
